package net.jalbum.filters;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

import net.jalbum.filterManager.FilterProperties.FilterCategory;
import se.datadosen.jalbum.Msg;

public class SepiaFilterPlugin extends BasicFilter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6592860195353596506L;
	protected int strength = 100;
	protected SepiaControl sepiaControl;

	public SepiaFilterPlugin() {
		this.name = Msg.getString(this, "filters.sepia.name");
		this.shortName = Msg.getString(this, "filters.sepia.shortName");
		this.icon = new ImageIcon(this.getClass().getResource("res/sepia.png"));
		this.author = "David Fichtmueller";
		this.version = "1.0";
		this.description = Msg.getString(this, "filters.sepia.description");
		this.category = FilterCategory.OTHER;
		this.prescale = false;
		this.postscale = true;

		this.sepiaControl = new SepiaControl(this);
	}

	@Override
	public JPanel getControls() {
		return this.sepiaControl;
	}

	/**
	 * We never touch the original image so avoid cloning
	 * @param bi
	 * @return
	 */
	@Override
	protected BufferedImage cloneBufferedImage(final BufferedImage bi) {
		return bi;
	}

	@Override
	public BufferedImage renderImage(final BufferedImage bi) {
		final BufferedImage out = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
		for (int x = 0; x < bi.getWidth(); x++) {
			for (int y = 0; y < bi.getHeight(); y++) {
				int rgb = bi.getRGB(x, y);

				// get the rgb-values
				final int alpha = (int) ((rgb & 0xff000000l) >> 24);
				final int r = ((rgb & 0x00ff0000) >> 16);
				final int g = ((rgb & 0x0000ff00) >> 8);
				final int b = ((rgb & 0x000000ff));

				final int gray = (int) (0.299 * r + 0.587 * g + 0.114 * b);

				// make sepia tone
				int rn = (int) ((gray * 1.3) * ((float) this.strength / 100) + r * (1 - ((float) this.strength / 100)));
				if (rn > 255) {
					rn = 255;
				}
				final int gn = (int) ((gray) * ((float) this.strength / 100) + g * (1 - ((float) this.strength / 100)));
				final int bn = (int) ((gray * 2 / 3) * ((float) this.strength / 100) + b * (1 - ((float) this.strength / 100)));

				rgb = ((alpha & 0xff) << 24) | ((rn & 0xff) << 16) | ((gn & 0xff) << 8) | (bn & 0xff);
				out.setRGB(x, y, rgb);
			}
		}
		return out;
	}

	@Override
	public void paint(final Graphics g) {
		// draw the current version of the image
		super.paint(g);
	}

	public int getStrength() {
		return this.strength;
	}

	public void setStrength(final int strength) {
		this.strength = strength;
	}
}
